package com.zt.java.nio;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.Selector;

/**
 * @ClassName: FileNio
 * @Description: FileNio
 * @Author: tao.zhang1
 * @Date: 2019/9/11 15:09
 * @Version: V1.0
 **/
public class FileNio {
    public static void main(String[] args) throws  Exception{
        //初始化
        FileInputStream inputStream = new FileInputStream(new File("/data.txt"));
        FileChannel fileChannel = inputStream.getChannel();
        //读取文件
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        int num = fileChannel.read(readBuffer);
        //写入到文件内容
        ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
        writeBuffer.put("随机写入一些内容到 Buffer 中".getBytes());
        // Buffer 切换为读模式
        writeBuffer.flip();
        while(writeBuffer.hasRemaining()) {
            // 将 Buffer 中的内容写入文件
            fileChannel.write(writeBuffer);
        }
    }
}
